#ifndef CODEEDITING_H
#define CODEEDITING_H

#include"highlighter/codehighlighter.h"

#include <QScrollBar>
// #include <memove>
#include <QThread>
#include <QFile>
#include <QFileInfo>
#include <QWidget>
#include <QMutex>
#include <QPlainTextEdit>

class FileLoader ;

namespace Ui {
class CodeEditing;
}
class CodeEditing : public QWidget
{
    Q_OBJECT

public:
    explicit CodeEditing(const QString& name, QWidget *parent = nullptr);
    ~CodeEditing();
    void loadText(const QString &filePath);
    void linguisticType(const QString &type);
    void saveFile();

    void ChangeHighlighting(const Language language);

signals:
    void amend(const bool);

private slots:
    void on_redact_blockCountChanged(int newBlockCount);
    void textChanged();

    void on_redact_cursorPositionChanged();

private:
    void lineNumber(const int lastTime, int change);
    // 高亮单词并设置背景颜色
    void highlightWordWithBackground(QTextCursor cursor);

private:
    Ui::CodeEditing *ui;
    int lastTime = 0;
    bool saveIF = true, toLoadIF = true;
    QString filePath{};
    QString fileName{};

    std::unique_ptr<CodeHighlighter> highlighter = nullptr;

    QThread *fileLoaderThread;
    FileLoader *fileLoader;
};

class FileLoader : public QObject {
    Q_OBJECT
public:
    explicit FileLoader(QTextStream *in, QObject *parent = nullptr)
        : QObject(parent), in(in) {}

signals:
    void chunkLoaded(const QString &chunk);
    void finished();

public slots:
    void loadFile(){
        while (!in->atEnd()) {
            emit chunkLoaded(in->read(20480));
            QThread::msleep(250);  // 模拟延迟，防止阻塞
        }
        emit finished();
    }

private:
    QTextStream *in;
};

#endif // CODEEDITING_H
